/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.shortlink.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shortlink.pojos.dto.dataobject.UserInfoDO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.shortlink.common.constants.JwtConstant.*;
import static com.shortlink.common.constants.UserConstant.*;

/**
 * JWT 工具类
 */
@Slf4j
public final class JWTUtil {



    /**
     * 生成用户 Token
     *
     * @param userInfo 用户信息
     * @return 用户访问 Token
     */
    public static String generateAccessToken(UserInfoDO userInfo) {

        Map<String, Object> customerUserMap = new HashMap<>();

        customerUserMap.put(USER_ID_KEY, userInfo.getId());
        customerUserMap.put(USER_NAME_KEY, userInfo.getUsername());

        String jwtToken = Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .setIssuedAt(new Date())
                .setIssuer(ISS)
                .setSubject(JSON.toJSONString(customerUserMap))
//                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION * 1000))
                .compact();

        return TOKEN_PREFIX + jwtToken;
    }

    /**
     * 解析用户 Token
     *
     * @param jwtToken 用户访问 Token
     * @return 用户信息
     */
    public static UserInfoDO parseJwtToken(String jwtToken) {
        if (StringUtils.hasText(jwtToken)) {
            String actualJwtToken = jwtToken.replace(TOKEN_PREFIX, "");
            try {
                Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(actualJwtToken).getBody();

//                Date expiration = claims.getExpiration();
//                if (expiration.after(new Date())) {
//                    String subject = claims.getSubject();
//                    JSONObject subjectJson = JSON.parseObject(subject);
//                    Long userId = subjectJson.getLong(USER_ID_KEY);
//                    String username = subjectJson.getString(USER_NAME_KEY);
//                    return new UserInfoDO(userId, username);
//                }

                String subject = claims.getSubject();
                JSONObject subjectJson = JSON.parseObject(subject);
                Long userId = subjectJson.getLong(USER_ID_KEY);
                String username = subjectJson.getString(USER_NAME_KEY);
                return new UserInfoDO(userId, username);

            } catch (ExpiredJwtException ignored) {
            } catch (Exception ex) {
                log.error("JWT Token解析失败，请检查", ex);
            }
        }
        return null;
    }
}